﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProjectCloth.FrmUI
{
    public class Helper
    {
        public static void SetValue(string key, string value)
        {
            //增加的内容写在appSettings段下 <add key="RegCode" value="0"/>  
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] == null)
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value = value;
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件   
        }
        public static void ExportDgv(DataGridView dgv, string xlxName)
        {
            try
            {
                FolderBrowserDialog fpath = new FolderBrowserDialog();
                fpath.ShowDialog();
                var path = fpath.SelectedPath;
                if (string.IsNullOrEmpty(path))
                {
                    MessageBox.Show("请选择保存路径！");
                    return;
                }
                var dt = GetDgvToTable(dgv);
                //获取指定虚拟路径的物理路径
                //string path ="D:\\";

                //读取 License 文件
                //Stream stream = (Stream)File.OpenRead(path);

                //注册 License
                //Aspose.Cells.License li = new Aspose.Cells.License();
                //li.SetLicense(stream);

                //创建一个工作簿
                Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();

                //创建一个 sheet 表
                Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];

                //设置 sheet 表名称
                worksheet.Name = dt.TableName;

                Aspose.Cells.Cell cell;

                int rowIndex = 0;   //行的起始下标为 0
                int colIndex = 0;   //列的起始下标为 0

                //设置列名
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    //获取第一行的每个单元格
                    cell = worksheet.Cells[rowIndex, colIndex + i];

                    //设置列名
                    cell.PutValue(dt.Columns[i].ColumnName);

                    //设置字体
                    //cell.Style.Font.Name = "Arial";

                    ////设置字体加粗
                    //cell.Style.Font.IsBold = true;

                    ////设置字体大小
                    //cell.Style.Font.Size = 12;

                    ////设置字体颜色
                    //cell.Style.Font.Color = System.Drawing.Color.Black;

                    ////设置背景色
                    //cell.Style.BackgroundColor = System.Drawing.Color.LightGreen;
                }

                //跳过第一行，第一行写入了列名
                rowIndex++;

                //写入数据
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        cell = worksheet.Cells[rowIndex + i, colIndex + j];

                        cell.PutValue(dt.Rows[i][j]);
                    }
                }

                //自动列宽
                worksheet.AutoFitColumns();

                //设置导出文件路径
                //path = HttpContext.Current.Server.MapPath("Export/");

                //设置新建文件路径及名称
                string savePath = path + "\\" + xlxName + "-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";

                //创建文件
                FileStream file = new FileStream(savePath, FileMode.CreateNew);

                //关闭释放流，不然没办法写入数据
                file.Close();
                file.Dispose();

                //保存至指定路径
                workbook.Save(savePath);

                MessageBox.Show("导出成功！");
                //或者使用下面的方法，输出到浏览器下载。
                //byte[] bytes = workbook.SaveToStream().ToArray();
                //OutputClient(bytes);

                worksheet = null;
                workbook = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出失败！" + ex.ToString());
            }
        }
        /// <summary>
        /// 绑定DataGridView数据到DataTable
        /// </summary>
        /// <param name="dgv">复制数据的DataGridView</param>
        /// <returns>返回的绑定数据后的DataTable</returns>
        public static DataTable GetDgvToTable(DataGridView dgv)
        {
            DataTable dt = new DataTable();
            // 列强制转换
            for (int count = 0; count < dgv.Columns.Count; count++)
            {
                DataColumn dc = new DataColumn(dgv.Columns[count].HeaderText.ToString());
                dt.Columns.Add(dc);
            }
            // 循环行
            for (int count = 0; count < dgv.Rows.Count; count++)
            {
                DataRow dr = dt.NewRow();
                for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
                {
                    if (Convert.ToString(dgv.Rows[count].Cells[countsub].Value).Length > 0)
                        dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value);
                    else
                    if (!string.IsNullOrEmpty(dgv.Rows[count].Cells[countsub].EditedFormattedValue.ToString()))
                        dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].EditedFormattedValue);
                    else
                        dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
        public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");//这里的 loginfo 和 log4net.config 里的名字要一样
        public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");//这里的 logerror 和 log4net.config 里的名字要一样
        public static void WriteLog(string info)
        {
            if (loginfo.IsInfoEnabled)
            {
                loginfo.Info(info);
            }
        }

        public static void WriteLog(string info, Exception ex)
        {
            if (logerror.IsErrorEnabled)
            {
                logerror.Error(info, ex);
            }
        }
        public static int GetIntFromCell(DataGridViewCell cell)
        {
            var cellValue = "0" + GetStringFromCell(cell);
            int result;
            if (int.TryParse(cellValue, out result)) return result;
            else return -1;
        }
        public static decimal GetDecimalFromCell(DataGridViewCell cell)
        {
            var cellValue = "0" + GetStringFromCell(cell);
            decimal result;
            if (decimal.TryParse(cellValue, out result)) return result;
            else return -1;
        }
        public static double GetDoubleFromCell(DataGridViewCell cell)
        {
            var cellValue = "0" + GetStringFromCell(cell);
            double result;
            if (double.TryParse(cellValue, out result)) return result;
            else return -1;
        }
        public static string GetStringFromCell(DataGridViewCell cell)
        {
            if (cell == null || cell.Value == null || string.IsNullOrEmpty(cell.Value.ToString()))
                return "";
            else return cell.Value.ToString();
        }
    }
}
namespace System.Collections.Generic
{
    public static class IEnumerableExtensions
    {
        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }
    }

}